package com.huihui.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.huihui.R;
import com.huihui.base.BaseActivity;
import com.huihui.datamanager.AppManager;
import com.huihui.eventbus.WxLoginSuccess;
import com.huihui.network.HttpContants;
import com.huihui.network.OkHttpRequest;
import com.huihui.network.base.CallBackUtil;
import com.huihui.network.pojo.UserInfo;
import com.huihui.utils.Contants;
import com.huihui.utils.IntentUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 微信登录回调
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wxpay_entry);
        api = WXAPIFactory.createWXAPI(this, Contants.WEIXIN_APPID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }


    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {

        weixinLogin(baseResp);


        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
                break;
            default:
                break;
        }
    }

    private void weixinLogin(BaseResp baseResp){
        SendAuth.Resp sendResp = null;
        String code = "";
        if(baseResp != null && baseResp instanceof SendMessageToWX.Resp){
            finish();
        }
        if(baseResp != null && baseResp instanceof SendAuth.Resp){
            sendResp = (SendAuth.Resp) baseResp;
        }
        if(sendResp != null){
            code = sendResp.code;
        }
        if(!TextUtils.isEmpty(code)){
            //
            OkHttpRequest.getInstance().getAccessToeknWeixin(code, new CallBackUtil.CallBackString() {
                @Override
                public void onFailure(Call call, Exception e) {
                    Log.e("","");
                }

                @Override
                public void onResponse(String response) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        final String accesstoken = jsonObject.getString("access_token");
                        String openid = jsonObject.getString("openid");
                        String unionid = jsonObject.getString("unionid");
                        if(!TextUtils.isEmpty(accesstoken) && !TextUtils.isEmpty(openid)){
                            //获取微信信息
                            OkHttpRequest.getInstance().getWeixinInfo(accesstoken, openid, new CallBackString() {
                                @Override
                                public void onFailure(Call call, Exception e) {

                                }

                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject1 = new JSONObject(response);
                                        if(jsonObject1 != null){
                                            int sexInt = 0;
                                            String sex = jsonObject1.getString("sex");
                                            if(sex.equals(1)) {
                                                sexInt = 1;
                                            }else{
                                                sexInt = 0;
                                            }
                                            String nickName = jsonObject1.getString("nickname");
                                            String url = jsonObject1.getString("headimgurl");
                                            String unionid = jsonObject1.getString("unionid");
                                            OkHttpRequest.getInstance().saveUserByPlatform(HttpContants.saveUserByPlatform, unionid, nickName, url, sexInt,1, new CallBackString() {
                                                @Override
                                                public void onFailure(Call call, Exception e) {
                                                    Log.e("","");
                                                }

                                                @Override
                                                public void onResponse(String response) {
                                                    try {
                                                        JSONObject json = new JSONObject(response);
                                                        if(json.has(HttpContants.DATA)){
                                                            UserInfo userInfo = AppManager.getGson().fromJson(json.getString(HttpContants.DATA),UserInfo.class);
                                                            if(userInfo != null) {
                                                                if(userInfo.getUser_type() == 2){
                                                                    finish();
                                                                }else {
                                                                    Log.d("token", "登录成功返回的token = " + userInfo.getToken());
                                                                    AppManager.setUserInfo(userInfo);
                                                                    AppManager.setToken(userInfo.getToken());
                                                                    EventBus.getDefault().post(new WxLoginSuccess());
                                                                    finish();
                                                                }
                                                            }
                                                        }else {
                                                        }
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            });
                                            //上传头像 先下载下来
//                                            Glide.with(getContext()).load(url);
//                                            String str = "headphoto/";
//                                            String name = getUUID32();
//                                            String key = str + name + ".jpg";
//                                            upload(key,url);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }else{
            finish();
        }
    }
}
